#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/12 22:42
# @Author  : jize.liu
# @File    : main.py
# @声明     : 版权由 刘继泽 所有,如有疑问，需要帮助请联系刘继泽
from File_QC import Ui_MainWindow
import os, sys, winreg
import subprocess
import json
import time
import shutil
import ctypes
import pandas as pd
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QCheckBox, QVBoxLayout, QSplitter,QMessageBox,QMenu,QHeaderView,QSystemTrayIcon,QToolTip
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from PySide6.QtGui import QIcon,QColor,QBrush,QAction,QFont
from PySide6.QtCore import QThread, QObject, Qt
from PySide6 import QtCore, QtGui, QtWidgets,QtSql


class NewQLineEdit (QtWidgets.QPlainTextEdit) :
    def __init__(self , *args , **kwargs) :
        super ().__init__ (*args , **kwargs)
        self.setAcceptDrops (True)  # 删除没有影响，目前不确定（因为True和False测试结果一样）
        self.setEnabled (True)  # 删除没有影响，（因为True和False测试结果一样）

    def dragEnterEvent(self , event) :
        if event.mimeData ().hasUrls () :  # 当文件拖入此区域时为True
            event.accept ()  # 接受拖入文件
        else :
            event.ignore ()  # 忽略拖入文件

    def dropEvent(self , event) :  # 本方法为父类方法，本方法中的event为鼠标放事件对象
        urls = [u for u in event.mimeData ().urls ()]  # 范围文件路径的Qt内部类型对象列表，由于支持多个文件同时拖入所以使用列表存放
        #print(urls)
        text = ''
        for url in urls :
            #print(url.path ()[1 :])
            text += url.path ()[1 :] + "\n"
            self.setPlainText (text)  # 将Qt内部类型转换为字符串类型

class CustomTableWidget (QtWidgets.QTableWidget) :
    def __init__(self , parent = None) :
        super ().__init__ (parent)

    def contextMenuEvent(self , event) :
        menu = QMenu (self)

        # 添加菜单项
        action1 = QAction ("打开文件" , self)
        action2 = QAction ("菜单项2" , self)
        menu.addAction (action1)
        menu.addAction (action2)
        #print (action1.triggered.connect(self.currentItemChanged))


        # 显示菜单
        menu.exec(event.globalPos ())


class File_QC_win (Ui_MainWindow, QMainWindow) :
    def __init__(self):
        super(File_QC_win, self).__init__()
        self.setupUi(self)
        #self.load_widget()
        self.QCpath = "T:/ANI_Team/测试"
        self.setWindowTitle (self.getDisplayName ())

        self.Feedback_Text_Edit = NewQLineEdit (parent=self.layoutWidget)
        self.Feedback_Text_Edit.setMinimumSize (QtCore.QSize (200 , 0))
        self.Feedback_Text_Edit.setMaximumSize (QtCore.QSize (500 , 16777215))
        self.Feedback_Text_Edit.setObjectName ("Feedback_Text_Edit")
        self.verticalLayout.addWidget (self.Feedback_Text_Edit)



        self.Refresh_pushButton.clicked.connect(self.loading_Table_Widget)
        self.OK_pushButton.clicked.connect(self.SubmitWindow)
        self.loading_Table_Widget()
        #self.Feedback_Table_Widget.horizontalHeader ().setSectionResizeMode (QHeaderView.ResizeMode.ResizeToContents)  #自适应
        #self.Feedback_Table_Widget.horizontalHeader ().setDefaultSectionSize (150) #所有列宽
        self.Feedback_Table_Widget.setColumnWidth (0 , 200)  # 第一列宽度200
        self.Feedback_Table_Widget.setColumnWidth (1 , 100)  # 第一列宽度200
        self.Feedback_Table_Widget.setColumnWidth (2 , 100)  # 第一列宽度200
        self.Feedback_Table_Widget.setColumnWidth (3 , 100)  # 第一列宽度200
        self.Feedback_Table_Widget.setColumnWidth (4 , 100)  # 第一列宽度200
        self.Feedback_Table_Widget.setFont (QFont ("song",12)) #字体设置
        self.Feedback_Table_Widget.verticalHeader().setDefaultSectionSize(40)
        font  =self.Feedback_Table_Widget.horizontalHeader().font()
        font.setBold(1)
        self.Feedback_Table_Widget.horizontalHeader().setFont(font)
        # self.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        #self.Feedback_Table_Widget.horizontalHeader ().setSectionResizeMode (QHeaderView.ResizeToContents)
        self.Feedback_Table_Widget.currentItemChanged.connect (self.on_current_item_changed)
        self.Feedback_Table_Widget.setContextMenuPolicy (Qt.ContextMenuPolicy.CustomContextMenu) #右键菜单
        self.Feedback_Table_Widget.customContextMenuRequested.connect (self.tableWidget_VTest_menu) #右键菜单

    def tableWidget_VTest_menu(self, pos):
        """
        :return:
        """
        row_num = -1
        for i in self.Feedback_Table_Widget.selectionModel().selection().indexes():
            row_num = i.row()
        #print(self.Feedback_Table_Widget.currentRow ())
        Item  = self.Feedback_Table_Widget.item(self.Feedback_Table_Widget.currentRow (),0)
        #print(Item.text())

        if row_num < 500: # 表格生效的行数，501行点击右键，不会弹出菜单
            menu = QMenu() #实例化菜单
            item1 = menu.addAction(u"打开文件")
            action = menu.exec(self.Feedback_Table_Widget.mapToGlobal(pos))
        else:
            return
        if action == item1:
            mov_path = (os.path.join(self.QCpath ,Item.text (),Item.text ()+".mov"))
            try :
                #恶搞

                #QMessageBox.critical (self , '提示' , '真该死，文件没交上来，回去重交！！！')
                os.startfile(mov_path)
            except FileNotFoundError :
                return (QMessageBox.critical (self, '提示' , '没有找到文件，把制作人叫过来打一顿！！！'))
            except Exception as e :
                return ("发生了其他错误:" , str (e))


    def SubmitWindow(self) :
        text = self.Feedback_Text_Edit.toPlainText ()
        lines = text.split ('\n')  # 按换行符分割文本，得到每行的内容
        non_empty_lines = [line for line in lines if line.strip()]
        Fileinfo = {}
        for line in non_empty_lines :
            # 在这里处理每行的内容，例如打印每行
            UploadFilePath =  line
            #Uploadshotfolder = "C:/Users/jize.liu/Desktop/UploadFile"
            #for UploadFile in os.listdir (Uploadshotfolder):
                #UploadFile = "C:/Users/jize.liu/Desktop/A10_EP13S001c0980_ANI.mov"
                #UploadFilePath = os.path.join(Uploadshotfolder,UploadFile)
            File_basename =  (os.path.basename(UploadFilePath))
            File_name = File_basename.split(".")
            #print(File_name)
            QCFile_name_folder = os.path.join (self.QCpath, File_name[0]).replace ("\\" , "/")#创建镜头文件夹
            if not os.path.exists (QCFile_name_folder) :
                os.mkdir (QCFile_name_folder)
            QCsubmit_MovFile = (os.path.join (QCFile_name_folder , File_basename))

            file_Historyfolder = os.path.join (QCFile_name_folder , "History").replace ("\\" , "/")  # 创建镜头版本文件夹
            if not os.path.exists (file_Historyfolder) :
                os.mkdir (file_Historyfolder)
            info = {}
            #for File in os.listdir (QCFile_name_folder):
            FilesHistoryNum = []
            if os.path.exists (QCFile_name_folder + "/" + File_basename) :
                if len (os.listdir (file_Historyfolder)) :
                    for num in range (len (os.listdir (file_Historyfolder))) :
                        FilesHistoryNum.append (f"{num + 1  :02d}")
                    QCHistoryFile = os.path.join (file_Historyfolder , File_name[0] + "-v" + str (f"{len (FilesHistoryNum) + 1:02d}") + "." + File_name[1])
                    FilesHistoryNum.append (str (f"{len (FilesHistoryNum) + 1:02d}"))

                    shutil.copy (UploadFilePath , QCHistoryFile)
                    #shutil.move (QCsubmit_MovFile , QCHistoryFile)  # 剪切文件
                    shutil.copy (UploadFilePath , QCFile_name_folder)


                    info["QCversions_info"] = FilesHistoryNum
                '''
                else :  # 不存在历史文件
                    QCHistoryFile = (os.path.join (file_Historyfolder , File_name[0] + "-v01." + File_name[1]))
                    FilesHistoryNum.append ("01")
                    info["QCversions_info"] = FilesHistoryNum
                    shutil.move (QCsubmit_MovFile , QCHistoryFile)
                    shutil.copy (UploadFilePath , QCFile_name_folder)
                    print ("22222222222222222222")
                    '''

            else:
                FilesHistoryNum.append ("01")
                info["QCversions_info"] = FilesHistoryNum
                QCHistoryFile = (os.path.join (file_Historyfolder , File_name[0] + "-v01." + File_name[1]))

                shutil.copy (UploadFilePath , QCHistoryFile)
                shutil.copy (UploadFilePath , QCFile_name_folder)


            timestamp = os.path.getmtime (UploadFilePath)
            modified_date = time.strftime ("%Y-%m-%d" , time.localtime (timestamp))
            info["RevisionDate"] = modified_date
            info["Frame"] = self.get_frame_count (UploadFilePath)
            info["PC_Name"] = self.getDisplayName ()
            info["State"] = "等待"
            Fileinfo[File_name[0]] = info
        #print (Fileinfo)

        try :
            if os.path.exists (self.QCpath + "/SG.json"):
                data = self.reading_json()
                #print( bool (data))
                data.update (Fileinfo)
                #print ("更新JSON字符串")# 更新
                self.update_json (data)
            else:
                self.update_json(Fileinfo)
        except json.JSONDecodeError :
            #print ("JSON字符串无法解析，内容可能为空")
            self.reading_json()
        self.loading_Table_Widget()
    def on_current_item_changed(self, current, previous):
        if current:
            row = self.Feedback_Table_Widget.currentRow()
            col = self.Feedback_Table_Widget.currentColumn()
    def load_widget(self):
        self.Feedback_Table_Widget.horizontalHeader ().setVisible (True)  # 行头
        self.Feedback_Table_Widget.verticalHeader ().setVisible (False)  # 列头
        self.Feedback_Table_Widget.setSortingEnabled (True)  # 头排序


        self.Feedback_Table_Widget.setColumnCount (6)  # 列数
        self.Feedback_Table_Widget.setHorizontalHeaderLabels (['镜头','版本','制作人',"状态",'帧数','修改时间'])  # 字段名
        self.sel ('select * from table1')  # 查询

        '''
        folder ="C:/Users/jize.liu/Desktop/QC"
        folder_count = 0
        for  shotfolder in os.listdir(folder):
            self.Feedback_Table_Widget.setRowCount (len (os.listdir (folder)))  # 行数
            if os.path.isdir(os.path.join (folder , shotfolder)):

                self.Feedback_Table_Widget.setItem (folder_count , 0 ,self.InsertText(shotfolder))
                self.Feedback_Table_Widget.setCellWidget (folder_count , 2 , self.QCversions ())
                folder_count += 1'''

    def QCversions(self):
        combox = QtWidgets.QComboBox ()
        combox.addItems (["等待","通过","打回"])
        return combox

    def InsertText(self,shotfolder):
        item = QtWidgets.QTableWidgetItem (shotfolder)
        return item

    def loading_Table_Widget(self) :
        self.Feedback_Table_Widget.horizontalHeader ().setVisible (True)  # 行头
        self.Feedback_Table_Widget.verticalHeader ().setVisible (False)  # 列头
        self.Feedback_Table_Widget.setSortingEnabled (True)  # 头排序

        self.Feedback_Table_Widget.setColumnCount (6)  # 列数
        self.Feedback_Table_Widget.setHorizontalHeaderLabels (['镜头' , '版本' , '制作人' , "状态" , '帧数' , '修改时间'])  # 字段名

        #data =self.reading_json()
        try :
            if os.path.exists (self.QCpath + "/SG.json"):
                data = self.reading_json()
                #print( bool (data))
                #print ("更新JSON字符串")# 更新
                #self.update_json (data)
                self.Feedback_Table_Widget.setRowCount (len (data.keys ()))
                folder_count = 0
                for key , value in data.items () :
                    item = QtWidgets.QTableWidgetItem (key)
                    self.Feedback_Table_Widget.setItem (folder_count , 0 , item)
                    # 添加版本控件
                    self.Feedback_Table_Widget.setCellWidget (folder_count , 1 , self.infor_loding_QCversions (value["QCversions_info"]))

                    self.Feedback_Table_Widget.setItem (folder_count , 2 , self.infor_loding_PC_Name (value["PC_Name"]))
                    # 添加状态控件
                    self.Feedback_Table_Widget.setItem (folder_count , 3 , QtWidgets.QTableWidgetItem (value["State"]))
                    # 在表格中添加状态
                    self.Feedback_Table_Widget.setCellWidget (folder_count , 3 , self.infor_loding_State (value["State"],folder_count))

                    self.Feedback_Table_Widget.setItem (folder_count , 4 , self.infor_loding_Frame (value["Frame"]))
                    self.Feedback_Table_Widget.setItem (folder_count , 5 , self.infor_loding_RevisionDate (value["RevisionDate"]))
                    folder_count += 1
        except json.JSONDecodeError :
            data = self.reading_json ()
            return ("JSON字符串无法解析，内容可能为空")

    def infor_loding_PC_Name(self,PC_Name) :
        return QtWidgets.QTableWidgetItem (str(PC_Name))
    def infor_loding_RevisionDate(self,RevisionDate) :
        return QtWidgets.QTableWidgetItem (str(RevisionDate))
    def infor_loding_Frame(self,Frame) :
        return QtWidgets.QTableWidgetItem (str(Frame))
    def infor_loding_QCversions(self,QCversions_info) :
        combox = QtWidgets.QComboBox ()
        combox.addItems (QCversions_info)
        combox.setCurrentText (max(QCversions_info))
        return combox
    def infor_loding_State(self,State,folder_count) :
        self.combox = QtWidgets.QComboBox ()
        self.combox.addItems (["等待" , "通过" , "打回"])
        self.combox.setCurrentText (State)

        if self.combox.currentText () == "通过":
            self.combox.setStyleSheet ("background-color: green; color: white;")
        elif self.combox.currentText () ==   "打回":
            self.combox.setStyleSheet ("background-color: red; color: white;")
        elif self.combox.currentText () == "等待" :
            self.combox.setStyleSheet ("background-color: gray; color: white;")
        self.combox.currentIndexChanged.connect (self.print_current_text)

        return self.combox

    def print_current_text(self,index ) :
        combo_box = self.sender ()
        if isinstance (combo_box , QtWidgets.QComboBox) :
            row = -1
            column = -1
            for i in range (self.Feedback_Table_Widget.rowCount ()) :
                for j in range (self.Feedback_Table_Widget.columnCount ()) :
                    if self.Feedback_Table_Widget.cellWidget (i , j) == combo_box :
                        row = i
                        column = j
                        break
                if row != -1 :
                    break
            if row != -1 and column != -1 :
                selected_text = combo_box.itemText (index)
                #print (f"ComboBox 行 {row}, 列 {column}")
                #print (f"QComboBox  选择: {selected_text}")


            else :
                return ("ComboBox not found in table")
        item = self.Feedback_Table_Widget.item (row , 0)  # 获取当QComboBox改变时，表格对应的0号位对应的镜头名
        if item is not None :
            content = item.text ()  # 获取单元格的文本内容
            data = self.reading_json ()
            data[content]["State"] = selected_text
            self.update_json(data)
            #print(combo_box.currentText ())

            if combo_box.currentText () == "通过":
                combo_box.setStyleSheet ("background-color: green; color: white;")
                QC_OK_File = os.path.join (self.QCpath , "OK")
                if not os.path.exists(QC_OK_File) :
                    os.mkdir (QC_OK_File)
                #print(os.path.join (self.QCpath,content,content + ".mov"))
                #print(os.path.exists())
                if os.path.exists(os.path.join (self.QCpath,content,content + ".mov")):
                    shutil.copy (os.path.join (self.QCpath,content,content + ".mov") ,  os.path.join (QC_OK_File,content + ".mov"))
                else:
                    #print("555555555555555555555555555555555")
                    combo_box.setCurrentText ("等待")
                    combo_box.setStyleSheet ("background-color: gray; color: white;")
                    return (QMessageBox.critical (self, '提示' , '真该死，文件没交上来，回去重交！！！'))


            elif combo_box.currentText () ==   "打回":
                combo_box.setStyleSheet ("background-color: red; color: white;")
            elif self.combox.currentText () == "等待":
                self.combox.setStyleSheet ("background-color: gray; color: white;")
        '''    #表格颜色
        if selected_text == "通过" :
            for col in range (self.Feedback_Table_Widget.columnCount ()) :
                print (row , col)
                item = self.Feedback_Table_Widget.item (row , col)
                item.setBackground (QBrush (QColor ('red')))
                '''


    def reading_json(self ) :
        with open (self.QCpath + "/SG.json",'r') as file :
            data = json.load (file)
        return (data)
    def update_json(self,data) :#保存
        with open (self.QCpath + "/SG.json" , 'w') as file :
            json.dump (data , file , indent = 4 , ensure_ascii = False)
        return (data)
    def print_current_Row(self , current , previous) :
        if current :
            row = self.Feedback_Table_Widget.currentRow ()
            col = self.Feedback_Table_Widget.currentColumn ()
            #print (f"当前行: {row}, 当前列: {col}")

    def get_frame_count(self,video_path) :
        command = ["H:/RareWolf_Toolkit/Package/ffmpeg/ffprobe.exe" , "-v" , "error" , "-count_frames" , "-select_streams" , "v:0" , "-show_entries" , "stream=nb_read_frames" , "-of" , "default=nokey=1:noprint_wrappers=1" , video_path]
        #process = subprocess.Popen (command ,stdout = subprocess.PIPE , stderr = subprocess.STDOUT)#
        #output = process.communicate ()[0]

        startupinfo = subprocess.STARTUPINFO ()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        process = subprocess.Popen (command , startupinfo = startupinfo , stdout = subprocess.PIPE , stderr = subprocess.PIPE , shell = True)
        output , error = process.communicate ()


        frame_count = int (output)
        return frame_count

    def sel(self,sql):
        sqlmodel=QtSql.QSqlQueryModel()
        sqlmodel.setQuery(sql)
        rows=sqlmodel.rowCount()
        columns=sqlmodel.columnCount()
        #print(rows,columns)
        for i in range(rows):
            #print(i)
            for j in range(columns):
                newItem=QtWidgets.QTableWidgetItem(str( sqlmodel.record(i).value(j)))
                self.tableWidget.setItem(i,j,newItem)




    def getDisplayName(self) :
        GetUserNameEx = ctypes.windll.secur32.GetUserNameExW
        NameDisplay = 3
        size = ctypes.pointer (ctypes.c_ulong (0))
        GetUserNameEx (NameDisplay, None, size)
        nameBuffer = ctypes.create_unicode_buffer (size.contents.value)
        GetUserNameEx (NameDisplay, nameBuffer, size)
        computerName = os.popen ('hostname').read ()
        return (nameBuffer.value)


if __name__ == '__main__' :
    app = QApplication (sys.argv)
    window = File_QC_win ()
    window.show ()
    sys.exit (app.exec ())
